<template>
  <div v-loading="loading" class="grouped-notification-list-container">
    <!-- 筛选器 -->
    <div class="filter-bar">
      <el-form :model="queryParams" inline>
        <el-form-item label="阅读状态">
          <el-select
            v-model="queryParams.isRead"
            placeholder="全部"
            clearable
            style="width: 120px"
            @change="handleQuery"
          >
            <el-option label="未读" :value="0" />
            <el-option label="已读" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 聚合通知列表 -->
    <div v-if="groupedList.records.length > 0" class="grouped-notifications">
      <NotificationGroupCard
        v-for="notification in groupedList.records"
        :key="notification.groupKey"
        :notification="notification"
        @click="handleCardClick"
        @mark-read="handleMarkRead"
        @view-detail="handleViewDetail"
      />
    </div>

    <!-- 空状态 -->
    <el-empty v-else :description="emptyText" />

    <!-- 分页 -->
    <div v-if="groupedList.total > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :total="groupedList.total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @current-change="handleQuery"
        @size-change="handleQuery"
      />
    </div>

    <!-- 通知详情弹窗 -->
    <NotificationDetailDialog
      v-model="detailDialogVisible"
      :query="detailQuery"
      @mark-read="handleDetailMarkRead"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import NotificationGroupCard from "@/components/NotificationGroupCard.vue";
import NotificationDetailDialog from "@/components/NotificationDetailDialog.vue";
import type {
  GroupedNotification,
  GroupedNotificationQuery,
  NotificationGroupType,
  GroupedDetailQuery
} from "@/types/notification-grouped";
import type { PageResponse } from "@/api/notification-grouped";
import {
  getGroupedNotificationsApi,
  markGroupedNotificationsAsReadApi
} from "@/api/notification-grouped";

const router = useRouter();

interface Props {
  type?: NotificationGroupType;
}

interface Emits {
  (e: "refresh"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const loading = ref(false);
const detailDialogVisible = ref(false);
const detailQuery = ref<GroupedDetailQuery | undefined>();

// 查询参数
const queryParams = ref<GroupedNotificationQuery>({
  current: 1,
  size: 10,
  type: props.type,
  isRead: undefined
});

// 聚合通知列表
const groupedList = ref<PageResponse<GroupedNotification>>({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 0
});

// 空状态文本
const emptyText = computed(() => {
  const typeMap: Record<string, string> = {
    FOLLOW: "暂无关注通知",
    LIKE: "暂无点赞通知",
    COLLECT: "暂无收藏通知",
    COMMENT: "暂无评论通知",
    REPLY: "暂无回复通知",
    MENTION: "暂无@提及通知",
    SYSTEM: "暂无系统通知"
  };

  if (props.type && typeMap[props.type]) {
    return typeMap[props.type];
  }
  return "暂无通知";
});

// 加载聚合通知列表
const loadGroupedNotifications = async () => {
  loading.value = true;
  try {
    const response = await getGroupedNotificationsApi(queryParams.value);
    if (response.code === 200 && response.data) {
      groupedList.value = response.data;
    } else {
      ElMessage.error(response.message || "加载失败");
    }
  } catch (error) {
    console.error("加载聚合通知列表失败:", error);
    ElMessage.error("加载失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleQuery = () => {
  queryParams.value.current = 1;
  loadGroupedNotifications();
};

// 重置
const handleReset = () => {
  queryParams.value = {
    current: 1,
    size: 10,
    type: props.type,
    isRead: undefined
  };
  loadGroupedNotifications();
};

// 清理 URL，确保是客户端路径
const sanitizeUrl = (url: string): string => {
  if (!url) return url;

  let cleanUrl = url;

  // 如果是完整的 URL(包含协议),尝试提取路径部分
  try {
    if (url.startsWith("http://") || url.startsWith("https://")) {
      const urlObj = new URL(url);
      cleanUrl = urlObj.pathname + urlObj.search + urlObj.hash;
      console.log("🧹 清理完整 URL:", url, "-> ", cleanUrl);
    }
  } catch (e) {
    console.warn("⚠️ 无法解析 URL:", url, e);
  }

  // 将 /article/ 路径转换为 /user/article/ (用户端路径)
  if (cleanUrl.startsWith("/article/")) {
    cleanUrl = "/user" + cleanUrl;
    console.log("🔄 转换路径:", url, "-> ", cleanUrl);
  }

  return cleanUrl;
};

// 处理卡片点击
const handleCardClick = (notification: GroupedNotification) => {
  console.log("👆 点击通知卡片:", notification);
  console.log("🔗 target 信息:", notification.target);
  console.log("📍 原始 target.url:", notification.target?.url);

  // 使用后端返回的 target.url 字段进行跳转
  if (notification.target?.url) {
    const cleanUrl = sanitizeUrl(notification.target.url);
    console.log("✅ 有 URL，清理后:", cleanUrl);
    console.log("🚀 开始跳转...");
    router.push(cleanUrl);
  } else {
    console.warn("⚠️ 没有 target.url，无法跳转");
    ElMessage.warning("该通知暂无跳转链接，请点击“查看详情”按钮");
  }
};

// 处理标记已读
const handleMarkRead = async (notification: GroupedNotification) => {
  try {
    const response = await markGroupedNotificationsAsReadApi({
      type: notification.type,
      targetType: notification.targetType,
      targetId: notification.targetId
    });

    if (response.code === 200) {
      ElMessage.success("已标记为已读");
      // 更新本地状态
      const index = groupedList.value.records.findIndex(
        item => item.groupKey === notification.groupKey
      );
      if (index !== -1) {
        groupedList.value.records[index].allRead = true;
        groupedList.value.records[index].unreadCount = 0;
      }
      emit("refresh");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("标记已读失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理查看详情
const handleViewDetail = (notification: GroupedNotification) => {
  detailQuery.value = {
    type: notification.type,
    targetType: notification.targetType,
    targetId: notification.targetId
  };
  detailDialogVisible.value = true;
};

// 处理详情弹窗中标记已读
const handleDetailMarkRead = () => {
  loadGroupedNotifications();
  emit("refresh");
};

// 组件挂载时加载数据
onMounted(() => {
  loadGroupedNotifications();
});

// 暴露方法供父组件调用
defineExpose({
  loadGroupedNotifications
});
</script>

<style scoped lang="scss">
// 移动端适配
@media screen and (width <= 768px) {
  .grouped-notification-list-container {
    .filter-bar {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;

      :deep(.el-form) {
        width: 100%;
      }

      :deep(.el-form-item) {
        width: 100%;

        .el-select {
          width: 100% !important;
        }
      }
    }

    .pagination-wrapper {
      :deep(.el-pagination) {
        .el-pagination__sizes {
          display: none;
        }

        .el-pagination__jump {
          display: none;
        }
      }
    }
  }
}

.grouped-notification-list-container {
  .filter-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    margin-bottom: 16px;
    background-color: #f5f7fa;
    border-radius: 8px;

    :deep(.el-form) {
      margin: 0;
    }

    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }

  .grouped-notifications {
    margin-bottom: 16px;
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>
